package com.juzipi.demo.io;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class IOServer {

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(9898);
        while (true){
            //使用阻塞的方式获取新的连接
            Socket socket = serverSocket.accept();

            //每个客户端连接的时候，创建新线程处理
            new Thread(){
                @Override
                public void run() {
                    String name = Thread.currentThread().getName();

                    try {
                        byte[] bytes = new byte[1024];
                        InputStream inputStream = socket.getInputStream();

                        while (true){
                            int len;
                            //使用字节流的方式读取数据
                            int i = 0;
                            while ((len=inputStream.read(bytes))!=-1){
                                System.out.println(name+","+new String(bytes,0,len)+i);
                                i++;
                            }
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }.start();

        }
    }
}
